package com.yihu.wlyy.web.patient.followup;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.follow.FollowUpItemRecord;
import com.yihu.wlyy.entity.follow.FollowUpItemRecordAnswer;
import com.yihu.wlyy.entity.follow.FollowUpItemRecordQuestion;
import com.yihu.wlyy.entity.follow.FollowUpItemRecordQuestionOption;
import com.yihu.wlyy.entity.follow.FollowUpPlan;
import com.yihu.wlyy.entity.follow.FollowUpPlanStageItem;
import com.yihu.wlyy.entity.follow.FollowUpPlanStageItemQuestion;
import com.yihu.wlyy.entity.follow.FollowUpSummary;
import com.yihu.wlyy.repository.DoctorDao;
import com.yihu.wlyy.repository.FollowUpItemRecordAnswerDao;
import com.yihu.wlyy.repository.FollowUpItemRecordDao;
import com.yihu.wlyy.repository.FollowUpItemRecordQuestionDao;
import com.yihu.wlyy.repository.FollowUpItemRecordQuestionOptionDao;
import com.yihu.wlyy.repository.FollowUpPlanDao;
import com.yihu.wlyy.repository.FollowUpPlanStageDao;
import com.yihu.wlyy.repository.FollowUpPlanStageItemDao;
import com.yihu.wlyy.repository.FollowUpPlanStageItemQuestionDao;
import com.yihu.wlyy.repository.FollowUpSummaryDao;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordAnswerVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordDetailVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordQuestionOptionVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordQuestionVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowupPlanVO;

@Service("patientFollowUpService")
public class PatientFollowUpService {
	@Autowired
	private FollowUpPlanDao followUpPlanDao;// 计划Dao
	@Autowired
	private FollowUpPlanStageDao followUpPlanStageDao;// 阶段dao
	@Autowired
	private FollowUpPlanStageItemDao followUpPlanStageItemDao;// 随访dao
	@Autowired
	private FollowUpItemRecordDao followUpItemRecordDao;// 周期dao
	@Autowired
	private FollowUpPlanStageItemQuestionDao followUpPlanStageItemQuestionDao;
	@Autowired
	private FollowUpItemRecordQuestionDao followUpItemRecordQuestionDao; // 周期问题Dao
	@Autowired
	private FollowUpItemRecordQuestionOptionDao followUpItemRecordQuestionOptionDao;// 周期选项dao
	@Autowired
	private FollowUpItemRecordAnswerDao followUpItemRecordAnswerDao;// 周期答案dao
	@Autowired
	private FollowUpSummaryDao followUpSummaryDao;
	@Autowired
	private DoctorDao doctorDao;

	public List<FollowUpItemRecord> getFollowUpPlanStageItemListByPlanCode(
			String userid, String planCode, String title, String type) {
		if (!StringUtils.isEmpty(planCode)) {
			return followUpItemRecordDao
					.getFollowUpPlanStageItemListByPlanCode(planCode);
		} else if (!StringUtils.isEmpty(type)) {
			return followUpItemRecordDao
					.getFollowUpPlanStageItemListByPlanCodeAndType(planCode,
							type);
		} else {
			List<FollowUpItemRecord> returnFollowUpItemRecord = new ArrayList<FollowUpItemRecord>();
			List<FollowUpPlan> followUpPlans = followUpPlanDao
					.findByPatient(userid);
			for (FollowUpPlan followUpPlan : followUpPlans) {
				List<FollowUpItemRecord> data = followUpItemRecordDao
						.getFollowUpPlanStageItemListByPlanCode(followUpPlan
								.getCode());
				returnFollowUpItemRecord.addAll(data);
			}
			return returnFollowUpItemRecord;
		}
	}

	public List<FollowupPlanVO> followupPlanList(String userId, long id,
			int pagesize, String title) throws Exception {
		List<FollowupPlanVO> returnList = new ArrayList<FollowupPlanVO>();
		if (pagesize <= 0) {
			pagesize = 10;
		}

		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize);
		// 设置查询条件

		Page<FollowUpPlan> followUpPlans = null;
		// 得到当前用户的计划
		if (StringUtils.isEmpty(title)) {
			if (id > 0) {
				followUpPlans = followUpPlanDao.getfollowupPlanListLeft(userId,
						id, pageRequest);
			} else {
				followUpPlans = followUpPlanDao.getfollowupPlanListLeft(userId,
						pageRequest);
			}
		} else {
			if (id > 0) {
				followUpPlans = followUpPlanDao.getfollowupPlanListLeft(userId,
						id, title, pageRequest);
			} else {
				followUpPlans = followUpPlanDao.getfollowupPlanListLeft(userId,
						title, pageRequest);
			}
		}
		if (followUpPlans != null) {
			for (FollowUpPlan followUpPlan : followUpPlans) {
				FollowupPlanVO followupPlanVO = new FollowupPlanVO();
				BeanUtils.copyProperties(followUpPlan, followupPlanVO);
				Doctor doctor = doctorDao
						.findByCode(followupPlanVO.getDoctor());
				followupPlanVO.setDoctorPhoto(doctor.getPhoto());
				returnList.add(followupPlanVO);
			}
		}
		return returnList;
	}

	public FollowUpItemRecordDetailVO getFollowUpItemRecordDetailById(
			String recoredCode) {
		FollowUpItemRecordDetailVO followUpItemRecordDetailVO = new FollowUpItemRecordDetailVO();
		FollowUpItemRecord followUpItemRecord = followUpItemRecordDao
				.getFollowUpItemRecordByCode(recoredCode);
		BeanUtils
				.copyProperties(followUpItemRecord, followUpItemRecordDetailVO);

		FollowUpPlan followUpPlan = followUpPlanDao
				.findByCode(followUpItemRecord.getPlan());
		followUpItemRecordDetailVO.setDoctor(followUpPlan.getDoctor());
		followUpItemRecordDetailVO.setDoctorName(followUpPlan.getDoctorName());
		// 得到本次隨訪週期的所有問題
		List<FollowUpItemRecordQuestion> followUpItemRecordQuestions = followUpItemRecordQuestionDao
				.getFollowUpItemRecordQuestionByRecoredCode(recoredCode);
		for (FollowUpItemRecordQuestion followUpItemRecordQuestion : followUpItemRecordQuestions) {
			FollowUpItemRecordQuestionVO followUpItemRecordQuestionVO = new FollowUpItemRecordQuestionVO();
			BeanUtils.copyProperties(followUpItemRecordQuestion,
					followUpItemRecordQuestionVO);
			// 得到问题的所有选项
			List<FollowUpItemRecordQuestionOption> FollowUpItemRecordQuestionOptions = followUpItemRecordQuestionOptionDao
					.findByRecordAndQuestion(recoredCode,followUpItemRecordQuestion.getCode());
			// 设置问题的所有选项
			List<FollowUpItemRecordQuestionOptionVO> FollowUpItemRecordQuestionOptionVOs = new ArrayList<FollowUpItemRecordQuestionOptionVO>();
			for (FollowUpItemRecordQuestionOption followUpItemRecordQuestionOption : FollowUpItemRecordQuestionOptions) {
				FollowUpItemRecordQuestionOptionVO followUpItemRecordQuestionOptionVO = new FollowUpItemRecordQuestionOptionVO();
				BeanUtils.copyProperties(followUpItemRecordQuestionOption,
						followUpItemRecordQuestionOptionVO);
				FollowUpItemRecordQuestionOptionVOs
						.add(followUpItemRecordQuestionOptionVO);
			}
			followUpItemRecordQuestionVO
					.setFollowUpItemRecordQuestionOptions(FollowUpItemRecordQuestionOptionVOs);
			// 如果已经回答 设置答案
			List<FollowUpItemRecordAnswer> followUpItemRecordAnswers = followUpItemRecordAnswerDao
					.findByRecordCodeAndQuestion(recoredCode,followUpItemRecordQuestion.getCode());
			// 判断是否有答案
			if (followUpItemRecordAnswers != null
					&& followUpItemRecordAnswers.size() > 0) {
				for (FollowUpItemRecordAnswer followUpItemRecordAnswer : followUpItemRecordAnswers) {
					FollowUpItemRecordAnswerVO followUpItemRecordAnswerVO = new FollowUpItemRecordAnswerVO();
					BeanUtils.copyProperties(followUpItemRecordAnswer,
							followUpItemRecordAnswerVO);
					followUpItemRecordQuestionVO
							.getFollowUpItemRecordAnswerVOs().add(
									followUpItemRecordAnswerVO);
				}
			}
			followUpItemRecordDetailVO.getFollowUpItemRecordQuestionVO().add(
					followUpItemRecordQuestionVO);
		}

		return followUpItemRecordDetailVO;
	}

	public JSONObject getPlanDetail(String planCode) {
		JSONObject jo = new JSONObject();
		FollowUpPlan followUpPlan = followUpPlanDao.findByCode(planCode);
		jo.put("title", followUpPlan.getTitle());
		jo.put("doctorName", followUpPlan.getDoctorName());
		jo.put("czrq", DateUtil.dateToStrShort(followUpPlan.getCzrq()));
		jo.put("wjAmount", followUpPlan.getWjAmount());
		jo.put("wjFinishAmount", followUpPlan.getWjFinishAmount());
		jo.put("tcAmount", followUpPlan.getTcAmount());
		jo.put("tcFinishAmount", followUpPlan.getTcFinishAmount());
		jo.put("planCode", followUpPlan.getCode());
		List<FollowUpSummary> followUpSummarys = followUpSummaryDao
				.findByPlanCodeAndType(planCode);
		JSONArray ja = new JSONArray();
		for (FollowUpSummary followUpSummary : followUpSummarys) {
			JSONObject joTemp = new JSONObject();
			joTemp.put("summary", followUpSummary.getSummary());
			joTemp.put("doctorName", followUpSummary.getDoctorName());
			joTemp.put("type", followUpSummary.getType());
			// 1、计划 2、阶段 3、随访项 4、随访纪录
			switch (followUpSummary.getType()) {
			case 1:
				joTemp.put("typeName", "计划");
				break;
			case 2:
				joTemp.put("typeName", "阶段");
				break;
			case 3:
				joTemp.put("typeName", "随访项 ");
				break;
			case 4:
				joTemp.put("typeName", "随访纪录");
				break;
			}
			joTemp.put("czrq",
					DateUtil.dateToStrLong(followUpSummary.getCzrq()));
			Doctor doctor = doctorDao.findByCode(followUpSummary.getDoctor());
			joTemp.put("photo", doctor == null ? "" : doctor.getPhoto());
			// joTemp。put
			ja.put(joTemp);
		}
		jo.put("docSummary", ja);
		return jo;
	}

	public JSONObject getItemDetail(long id, int pageSize, String itemCode) {
		JSONObject jo = new JSONObject();
		// 根据计划code找出所有的随访 时间倒叙
		FollowUpPlanStageItem followUpPlanStageItem = followUpPlanStageItemDao
				.findByCode(itemCode);
		jo.put("title", followUpPlanStageItem.getTitle());
		JSONArray ja = new JSONArray();
		// 根据随访code找出每次随访的总结
		PageRequest pageRequest = new PageRequest(0, pageSize);
		Page<FollowUpSummary> followUpSummarys = null;
		if (id > 0) {

			followUpSummarys = followUpSummaryDao.findByItemCode(itemCode, id,
					pageRequest);
		} else {
			followUpSummarys = followUpSummaryDao.findByItemCode(itemCode,
					pageRequest);
		}

		if (followUpSummarys != null && followUpSummarys.getSize() > 0) {
			for (FollowUpSummary followUpSummary : followUpSummarys) {

				JSONObject joTemp = new JSONObject();
				joTemp.put("summary", followUpSummary.getSummary());
				joTemp.put("czrq",
						DateUtil.dateToStrShort(followUpSummary.getCzrq()));
				joTemp.put("title", followUpPlanStageItem.getTitle());
				joTemp.put("doctorName", followUpSummary.getDoctorName());
				joTemp.put("id", followUpSummary.getId());
				joTemp.put("photo",
						doctorDao.findByCode(followUpSummary.getDoctor())
								.getPhoto());
				ja.put(joTemp);
			}
		}
		jo.put("summary", ja);
		return jo;
	}

	public JSONObject getFollowUpTZs(String question) {
		JSONObject jo = new JSONObject();
		List<FollowUpPlanStageItemQuestion> followUpPlanStageItemQuestions=followUpPlanStageItemQuestionDao.findByCode(question);
		jo.put("title", followUpPlanStageItemQuestions.get(0).getTitle());
		//根據questionCode找出所有問卷的答案 
		List<FollowUpItemRecordAnswer> followUpItemRecordAnswers=followUpItemRecordAnswerDao.findbyQuestion(question);
		JSONArray  jaTmep = new JSONArray();	
		for(FollowUpItemRecordAnswer followUpItemRecordAnswer: followUpItemRecordAnswers){
			JSONObject joTemp = new JSONObject();
			joTemp.put("answer", followUpItemRecordAnswer.getAnswer());
			joTemp.put("czrq", DateUtil.dateToStrShort(followUpItemRecordAnswer.getCzrq()));
			FollowUpItemRecordQuestionOption followUpItemRecordQuestionOption= followUpItemRecordQuestionOptionDao.findByCode(followUpItemRecordAnswer.getOption());
			joTemp.put("desc",followUpItemRecordQuestionOption.getDes());
			jaTmep.put(joTemp);
		}
		jo.put("datas", jaTmep);
		return jo;
	}

	/**
	 * 
	 * { titile:"随访计划title", question:{ 是否按时吃药:{ 2016-03-03:[吃了很多],
	 * 2016-03-04:[吃了很少，吃了不少] }.
	 * 
	 * 问题名字：{ 日期:[答案] } }
	 * 
	 * @param itemCode
	 * @return
	 */
	public JSONObject getFollowUpWJs(String itemCode) {
		FollowUpPlanStageItem followUpPlanStageItem = followUpPlanStageItemDao
				.findByCode(itemCode);
		// 根据随访code查找本次随访的所有问题
		List<FollowUpItemRecordQuestion> followUpItemRecordQuestions = followUpItemRecordQuestionDao
				.findByPlanAndStageAndItem(followUpPlanStageItem.getCode());

		JSONObject joTmep = new JSONObject();
		for (FollowUpItemRecordQuestion followUpItemRecordQuestion : followUpItemRecordQuestions) {
			if (followUpItemRecordQuestion != null) {
				// 找出答案
				List<FollowUpItemRecordAnswer> followUpItemRecordAnswers = followUpItemRecordAnswerDao
						.getFollowUpItemRecordAnswerByQuestionCode(followUpItemRecordQuestion
								.getCode());
				JSONObject answerJA = null;

				if (!joTmep.has(followUpItemRecordQuestion.getTitle())) {
					answerJA = new JSONObject();
				} else {
					answerJA = (JSONObject) joTmep
							.get(followUpItemRecordQuestion.getTitle());
				}
				JSONArray answerJO = new JSONArray();
				String key = "";
				for (FollowUpItemRecordAnswer followUpItemRecordAnswer : followUpItemRecordAnswers) {
					if (followUpItemRecordAnswer != null) {
						// 判断是问答还是单选或者多选
						if (followUpItemRecordQuestion.getType() == 3) {
							answerJO.put(followUpItemRecordAnswer.getAnswer());
						} else {
							FollowUpItemRecordQuestionOption followUpItemRecordQuestionOption = followUpItemRecordQuestionOptionDao
									.findByCode(followUpItemRecordAnswer
											.getOption());
							if (followUpItemRecordQuestionOption != null) {
								answerJO.put(followUpItemRecordQuestionOption
										.getDes());
							}
						}
						key = DateUtil.dateToStrLong(followUpItemRecordAnswer
								.getCzrq());
					}
				}
				answerJA.put(key, answerJO);
				joTmep.put(followUpItemRecordQuestion.getTitle(), answerJA);
			}
		}

		// 数据格式转换
		JSONObject returnJSONObjectTemp = new JSONObject();
		JSONArray jaTemp = new JSONArray();
		for (String key : joTmep.keySet()) {
			JSONObject jo = (JSONObject) joTmep.get(key);
			JSONArray answerJA = new JSONArray();
			for (String jokey : jo.keySet()) {
				JSONObject joAnswer = new JSONObject();
				if (!StringUtils.isEmpty(jokey)) {
					joAnswer.put("czrq", DateUtil.dateToStrShort(DateUtil
							.strToDateLong(jokey)));
					joAnswer.put("desc", jo.get(jokey));
					answerJA.put(joAnswer);
				}
			}
			jo = new JSONObject();
			jo.put("answer", answerJA);
			jo.put("title", key);
			jaTemp.put(jo);
		}
		returnJSONObjectTemp.put("title", followUpPlanStageItem.getTitle());
		returnJSONObjectTemp.put("question", jaTemp);
		return returnJSONObjectTemp;
	}

	@Transactional
	public void saveRecordAnswers(List<FollowUpItemRecordAnswer> asList) {
		// 保存答案
		followUpItemRecordAnswerDao.save(asList);
		// 修改对应的recored的标识 1问卷，2体测
		FollowUpItemRecordAnswer followUpItemRecordAnswer = asList.get(0);
		int type = followUpItemRecordAnswer.getType();
		if (type == 1) {
			// 1问卷
			FollowUpItemRecord followUpItemRecord = followUpItemRecordDao
					.findByCode(followUpItemRecordAnswer.getRecord());
			followUpItemRecord.setStatus(1);// 修改标识为已经完成
			followUpItemRecordDao.save(followUpItemRecord);
			// 修改计划的计数器
			FollowUpPlan followUpPlan = followUpPlanDao
					.findByCode(followUpItemRecord.getPlan());
			int count = followUpPlan.getWjFinishAmount();
			followUpPlan.setWjFinishAmount(count++);
		} else {
			// 2体测
			FollowUpItemRecord followUpItemRecord = followUpItemRecordDao
					.findByCode(followUpItemRecordAnswer.getRecord());
			String recordCode = followUpItemRecord.getCode();
			// 得到当前问卷的答案数
			List<FollowUpItemRecordAnswer> followUpItemRecordAnswers = followUpItemRecordAnswerDao
					.findByRecordDistinQuestion(recordCode);
			// 得到当前问卷的问题数目
			List<FollowUpItemRecordQuestion> followUpItemRecordQuestions = followUpItemRecordQuestionDao
					.findByRecord(recordCode);
			if (followUpItemRecordAnswers != null
					&& followUpItemRecordAnswers.size() > 0) {
				if (followUpItemRecordQuestions.size() == followUpItemRecordAnswers
						.size()) {
					followUpItemRecord.setStatus(1);// 修改标识为已经完成
					// 修改计划的计数器
					FollowUpPlan followUpPlan = followUpPlanDao
							.findByCode(followUpItemRecord.getPlan());
					int count = followUpPlan.getTcFinishAmount();
					followUpPlan.setTcAmount(count++);
					// 修改计划的计数器
				}
			}
		}
	}

	public JSONArray getTypeList(String itemCode) {
		JSONArray ja = new JSONArray();
		List<Integer> followUpItemRecordQuestions = followUpItemRecordQuestionDao
				.getByItemCodeDistinctType(itemCode);
		if (followUpItemRecordQuestions != null
				&& followUpItemRecordQuestions.size() > 0) {
			for (Integer index : followUpItemRecordQuestions) {
				JSONObject jo = new JSONObject();
				jo.put("index", index);
				jo.put("itemCode", itemCode);
				switch (index) {
				case 1:
					jo.put("indexName", "血糖");
					break;
				case 2:
					jo.put("indexName", "血压");
					break;
				case 3:
					jo.put("indexName", "体重");
					break;
				case 4:
					jo.put("indexName", "腰围");
					break;
				}
				ja.put(jo);
			}
		}
		return ja;
	}

	public JSONObject getItemList(String planCode, int type) {
		JSONObject jo = new JSONObject();
		FollowUpPlan followUpPlan = followUpPlanDao.findByCode(planCode);
		jo.put("title", followUpPlan.getTitle());
		List<String> itemCodes = followUpItemRecordDao
				.findByPlanCodeAndTypeDistinctItemCode(planCode, type);
		JSONArray ja = new JSONArray();
		if (itemCodes != null && itemCodes.size() > 0) {
			for (String itemCode : itemCodes) {
				FollowUpPlanStageItem followUpPlanStageItem = followUpPlanStageItemDao
						.findByCode(itemCode);
				JSONObject joTemp = new JSONObject();
				joTemp.put("title", followUpPlanStageItem.getTitle());
				joTemp.put("plan", followUpPlanStageItem.getPlan());
				joTemp.put("item", followUpPlanStageItem.getCode());
				joTemp.put("stage", followUpPlanStageItem.getStage());
				ja.put(joTemp);
			}
		}
		jo.put("item", ja);
		return jo;
	}

	public JSONArray getQuestionList(String itemCode) {
		JSONArray ja=new JSONArray();
		List<FollowUpPlanStageItemQuestion> followUpItemRecordQuestions=followUpPlanStageItemQuestionDao.findByItemCode(itemCode);
		for(FollowUpPlanStageItemQuestion followUpItemRecordQuestion:followUpItemRecordQuestions){
			JSONObject joTemp = new JSONObject();
				joTemp.put("title", followUpItemRecordQuestion.getTitle());
				joTemp.put("item", followUpItemRecordQuestion.getItem());
				joTemp.put("question", followUpItemRecordQuestion.getCode());
				ja.put(joTemp);
		}
		return ja;
	}

}
